#include <signal.h>

#include "signals.h"
#include "sim.h"

extern Simulator Sim;

struct sigaction sa;

/************************************************************
 * Signal Handlers: Could make more C++/OOP
 ************************************************************/

void SIGINT_handler (int signum)
{
    fprintf (stderr, "***** SIGINT_handler *****\n");
    Sim.fini ();
    exit (signum);
}

void SIGABRT_handler (int signum)
{
    fprintf (stderr, "***** SIGABRT_handler *****\n");
    Sim.fini ();
    exit (signum);
}

void SIGKILL_handler (int signum)
{
    fprintf (stderr, "***** SIGKILL_handler *****\n");
    Sim.fini ();
    exit (signum);
}

void SIGSEGV_handler (int signum)
{
    fprintf (stderr, "***** SIGSEGV_handler *****\n");
    Sim.fini ();
    exit (signum);
}

/** Dump stats, but don't exit.  */
void SIGUSR1_handler (int signum)
{
    Sim.dump_stats ();
}

void signal_hander_init (void)
{
    sigemptyset (&sa.sa_mask);
    sa.sa_flags = 0;

    sa.sa_handler = SIGINT_handler;
    sigaction (SIGINT, &sa, 0);

    sa.sa_handler = SIGABRT_handler;
    sigaction (SIGABRT, &sa, 0);

    sa.sa_handler = SIGKILL_handler;
    sigaction (SIGKILL, &sa, 0);

    sa.sa_handler = SIGSEGV_handler;
    sigaction (SIGSEGV, &sa, 0);

    sa.sa_handler = SIGUSR1_handler;
    sigaction (SIGUSR1, &sa, 0);
}


